package com.search_wheel.service;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.search_wheel.config.AiConfig;
import com.search_wheel.pojo.dto.AiExplanation;
import com.search_wheel.pojo.dto.AiRequest;
import com.search_wheel.pojo.dto.AiResponse;

import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

// 在AiService类的开头添加导入
import com.fasterxml.jackson.databind.DeserializationFeature;

@Service
public class AiService {

    @Autowired
    private AiConfig aiConfig;

    private ObjectMapper objectMapper = new ObjectMapper();
    private final OkHttpClient client;

    // 修改构造函数
    public AiService() {
        // 配置ObjectMapper - 忽略未知字段
        this.objectMapper = new ObjectMapper();
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
    }

    // 替换AiService中的getExplanationAsync方法
    public CompletableFuture<AiExplanation> getExplanationAsync(String keyword) {
        System.out.println("getExplanationAsync 被调用，keyword: " + keyword);
        System.out.println("AI配置检查 - enabled: " + aiConfig.isEnabled() +
                ", hasKeyword: " + StringUtils.hasText(keyword));

        if (!aiConfig.isEnabled()) {
            System.out.println("AI服务未启用");
            return CompletableFuture.completedFuture(
                    AiExplanation.error(keyword, "AI服务未启用"));
        }

        if (!StringUtils.hasText(keyword)) {
            System.out.println("关键词为空");
            return CompletableFuture.completedFuture(
                    AiExplanation.error(keyword, "关键词为空"));
        }

        System.out.println("开始创建异步任务...");
        return CompletableFuture.supplyAsync(() -> {
            System.out.println("异步任务开始执行...");
            try {
                AiExplanation result = getExplanation(keyword);
                System.out.println("异步任务执行完成，结果: " + result.isSuccess());
                return result;
            } catch (Exception e) {
                System.err.println("异步任务执行异常: " + e.getMessage());
                e.printStackTrace();
                return AiExplanation.error(keyword, "AI服务异常: " + e.getMessage());
            }
        });
    }

    // 替换AiService中的getExplanation方法
    public AiExplanation getExplanation(String keyword) {
        System.out.println("=== 开始同步AI请求 ===");
        System.out.println("API配置 - baseUrl: " + aiConfig.getBaseUrl());
        System.out.println("API配置 - model: " + aiConfig.getModel());
        System.out.println("API配置 - apiKey: " + (aiConfig.getApiKey() != null ?
                aiConfig.getApiKey().substring(0, 8) + "..." : "null"));

        try {
            // 构建请求
            System.out.println("构建请求...");
            AiRequest request = buildRequest(keyword);
            String requestJson = objectMapper.writeValueAsString(request);
            System.out.println("请求JSON长度: " + requestJson.length());

            RequestBody body = RequestBody.create(requestJson,
                    MediaType.get("application/json; charset=utf-8"));

            String url = aiConfig.getBaseUrl() + "chat/completions";
            System.out.println("请求URL: " + url);

            Request httpRequest = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "Bearer " + aiConfig.getApiKey())
                    .addHeader("Content-Type", "application/json")
                    .post(body)
                    .build();

            System.out.println("发送HTTP请求...");
            // 发送请求
            try (Response response = client.newCall(httpRequest).execute()) {
                System.out.println("收到响应 - 状态码: " + response.code());

                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "无响应体";
                    System.err.println("API请求失败 - 响应体: " + errorBody);
                    return AiExplanation.error(keyword,
                            "API请求失败: " + response.code() + " " + response.message());
                }

                String responseBody = response.body().string();
                System.out.println("响应体长度: " + responseBody.length());
                System.out.println("响应体前200字符: " + responseBody.substring(0,
                        Math.min(200, responseBody.length())));

                AiResponse aiResponse = objectMapper.readValue(responseBody, AiResponse.class);
                System.out.println("JSON解析成功");

                // 解析响应
                if (aiResponse.getChoices() != null && !aiResponse.getChoices().isEmpty()) {
                    String explanation = aiResponse.getChoices().get(0).getMessage().getContent();
                    System.out.println("获取到AI解释，长度: " + explanation.length());
                    return AiExplanation.success(keyword, explanation.trim());
                } else {
                    System.err.println("AI返回结果为空");
                    return AiExplanation.error(keyword, "AI返回结果为空");
                }
            }

        } catch (Exception e) {
            System.err.println("处理异常: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            e.printStackTrace();
            return AiExplanation.error(keyword, "处理异常: " + e.getMessage());
        }
    }

    /**
     * 构建AI请求
     */
    private AiRequest buildRequest(String keyword) {
        AiRequest request = new AiRequest();
        request.setModel(aiConfig.getModel());
        request.setTemperature(0.3);
        request.setMaxTokens(1000);

        // 构建提示词
        String prompt = buildPrompt(keyword);

        AiRequest.Message message = new AiRequest.Message("user", prompt);
        request.setMessages(Collections.singletonList(message));

        return request;
    }

    /**
     * 构建智能提示词
     */
    private String buildPrompt(String keyword) {
        return String.format(
                "请对搜索关键词'%s'进行智能解释和说明。要求：\n" +
                        "1. 如果是技术术语，请解释其含义、用途和特点\n" +
                        "2. 如果是概念词汇，请说明其定义和相关背景\n" +
                        "3. 如果是产品名称，请介绍其功能和特色\n" +
                        "4. 解释要简洁明了，控制在200字以内\n" +
                        "5. 使用通俗易懂的语言\n" +
                        "6. 如果关键词模糊或有多重含义，请选择最常见的解释\n\n" +
                        "关键词：%s", keyword, keyword);
    }
}
